<script setup lang="ts">
import { ref, reactive, h, onMounted, computed, watch } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import { ElMessage, ElTag, ElButton } from "element-plus";
import {
  getGithubAssets,
  getGithubAssetDetail,
  getDepartments,
} from "../../servers";
import DynamicForm from "@/components/DynamicForm";
import DynamicDetailDialog from "@/components/DynamicDetailDialog";
import type { DetailGroup } from "@/components/DynamicDetailDialog/types";

const props = defineProps<{
  task: string;
}>();

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const assetList = ref<any[]>([]);
const loading = ref(false);
const formRef = ref<any>(null);
const showDetailDialog = ref(false);
const currentDetailAsset = ref<any>(null);
const loadingDetail = ref(false);

// 部门选项
const departmentOptions = ref<Array<{ label: string; value: string }>>([]);

// 加载部门列表
const loadDepartments = async () => {
  try {
    const result = await getDepartments();
    if (result && typeof result === "object" && "departments" in result) {
      departmentOptions.value = [
        { label: "全部", value: "" },
        ...result.departments,
      ];
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取部门列表失败");
  }
};

// 筛选表单数据
const filterForm = reactive({
  source_type: "github", // 固定为 GitHub
  department: "",
  risk_level: "",
  status: "",
  keyword: "",
});

// 筛选表单配置
const formConfig = computed(() => [
  // {
  //   key: "source_type",
  //   name: "来源",
  //   type: "select" as const,
  //   defaultValue: "github",
  //   placeholder: "来源",
  //   params: {
  //     clearable: false,
  //     disabled: true,
  //   },
  //   options: [{ label: "GitHub", value: "github" }],
  //   labelWidth: "80px",
  // },
  {
    key: "department",
    name: "部门",
    type: "select" as const,
    defaultValue: "",
    placeholder: "全部",
    params: {
      clearable: true,
    },
    options: departmentOptions.value,
    labelWidth: "80px",
  },
  {
    key: "risk_level",
    name: "风险",
    type: "select" as const,
    defaultValue: "",
    placeholder: "全部",
    params: {
      clearable: true,
    },
    options: [
      { label: "全部", value: "" },
      { label: "高危", value: "high" },
      { label: "中危", value: "medium" },
      { label: "低危", value: "low" },
    ],
    labelWidth: "80px",
  },
  {
    key: "status",
    name: "状态",
    type: "select" as const,
    defaultValue: "",
    placeholder: "全部",
    params: {
      clearable: true,
    },
    options: [
      { label: "全部", value: "" },
      { label: "待处理", value: "pending" },
      { label: "已确认", value: "confirmed" },
      { label: "误报", value: "false_positive" },
    ],
    labelWidth: "80px",
  },
  {
    key: "keyword",
    name: "搜索",
    type: "input" as const,
    defaultValue: "",
    placeholder: "请输入关键词（仓库、文件路径等）",
    params: {
      clearable: true,
    },
    col: {
      span: 6,
    },
  },
]);

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (!bytes) return "-";
  if (bytes < 1024) return `${bytes} bytes`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
};

// 获取风险等级标签类型
const getRiskLevelTagType = (riskLevel: string) => {
  const riskMap: Record<
    string,
    "success" | "warning" | "info" | "danger" | ""
  > = {
    high: "danger",
    medium: "warning",
    low: "success",
  };
  return riskMap[riskLevel] || "info";
};

// 获取风险等级文本
const getRiskLevelText = (riskLevel: string) => {
  const riskMap: Record<string, string> = {
    high: "高危",
    medium: "中危",
    low: "低危",
  };
  return riskMap[riskLevel] || riskLevel || "-";
};

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap: Record<
    string,
    "success" | "warning" | "info" | "danger" | ""
  > = {
    pending: "warning",
    confirmed: "success",
    false_positive: "info",
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "待处理",
    confirmed: "已确认",
    false_positive: "误报",
  };
  return statusMap[status] || status || "-";
};

const historyColumns = ref<TableColumn[]>([
  {
    label: "ID",
    prop: "leak_id",
    show: true,
  },
  // {
  //   label: "仓库",
  //   prop: "repository_url",
  //   minWidth: 200,
  //   show: true,
  //   render: (row) => {
  //     return h(
  //       "div",
  //       { style: "display: flex; align-items: center; gap: 8px" },
  //       [
  //         h("span", { style: "flex: 1" }, row.repository_url || "-"),
  //         row.source_type === "github"
  //           ? h(ElTag, { type: "info", size: "small" }, () => "GitHub")
  //           : null,
  //       ]
  //     );
  //   },
  // },
  {
    label: "文件路径",
    prop: "file_path",
    show: true,
    render: (row) => {
      return h("div", [
        h("div", { style: "font-weight: 500" }, row.filename || "-"),
        h(
          "div",
          { style: "font-size: 12px; color: #909399; margin-top: 4px" },
          row.file_path || "-"
        ),
      ]);
    },
  },
  {
    label: "部门",
    prop: "responsible_department",
    show: true,
    render: (row) => row.responsible_department || "-",
  },
  {
    label: "风险",
    prop: "risk_level",
    show: true,
    render: (row) => {
      return h(
        ElTag,
        {
          type: getRiskLevelTagType(row.risk_level),
          size: "small",
        },
        () => getRiskLevelText(row.risk_level)
      );
    },
  },
  {
    label: "更新时间",
    prop: "updated_time",
    show: true,
  },
  {
    label: "操作",
    prop: "action",
    width: 120,
    show: true,
    slot: "asset_action",
    fixed: "right",
  },
]);

const fetchAssetList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
    };

    if (filterForm.department) {
      params.department = filterForm.department;
    }

    if (filterForm.risk_level) {
      params.risk_level = filterForm.risk_level;
    }

    if (filterForm.status) {
      params.status = filterForm.status;
    }

    if (filterForm.keyword?.trim()) {
      params.keyword = filterForm.keyword.trim();
    }

    const result = await getGithubAssets(params);

    assetList.value = result.data.assets || [];
    pagination.total = result.data.total || 0;
  } catch (error: any) {
    ElMessage.error(error?.message || "获取资产列表失败");
    assetList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchAssetList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchAssetList();
};

// 查看详情
const handleViewDetail = async (row: any) => {
  loadingDetail.value = true;
  showDetailDialog.value = true;
  try {
    // 使用资产ID获取详情
    const assetId = row.id || row.leak_id;
    if (!assetId) {
      ElMessage.warning("资产ID不存在");
      showDetailDialog.value = false;
      return;
    }

    const result = await getGithubAssetDetail(assetId);
    if (result.code === 2000 && result.data) {
      currentDetailAsset.value = result.data;
    } else {
      ElMessage.error(result.message || "获取资产详情失败");
      showDetailDialog.value = false;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取资产详情失败");
    showDetailDialog.value = false;
  } finally {
    loadingDetail.value = false;
  }
};

// 搜索
const handleSearch = (formData: Record<string, any>) => {
  Object.assign(filterForm, formData);
  pagination.currentPage = 1;
  fetchAssetList();
};

// 重置筛选
const handleReset = () => {
  filterForm.department = "";
  filterForm.risk_level = "";
  filterForm.status = "";
  filterForm.keyword = "";
  formRef.value?.resetFields();
  pagination.currentPage = 1;
  fetchAssetList();
};

// 详情分组数据
const detailGroups = computed<DetailGroup[]>(() => {
  if (!currentDetailAsset.value) return [];

  const asset = currentDetailAsset.value;

  return [
    {
      title: "基本信息",
      type: "normal" as const,
      items: [
        {
          key: "leak_id",
          label: "ID",
          value: asset.leak_id || "-",
        },
        {
          key: "repository_url",
          label: "仓库",
          value: asset.repository_url || "-",
          type: "custom" as const,
          slot: "repository_url",
          span: 2,
        },
        {
          key: "file_path",
          label: "文件路径",
          value: asset.file_path || "-",
          span: 2,
        },
        {
          key: "filename",
          label: "文件名",
          value: asset.filename || "-",
        },
        {
          key: "size",
          label: "文件大小",
          value: formatFileSize(asset.size),
        },
        {
          key: "detected_time",
          label: "检测时间",
          value: asset.detected_time || "-",
        },
      ],
    },
    {
      title: "资产信息",
      type: "normal" as const,
      items: [
        {
          key: "responsible_department",
          label: "责任部门",
          value: asset.responsible_department || "-",
        },
        {
          key: "risk_level",
          label: "风险等级",
          value: getRiskLevelText(asset.risk_level),
          type: "tag" as const,
          tagType: getRiskLevelTagType(asset.risk_level) as
            | "success"
            | "warning"
            | "info"
            | "danger"
            | "",
        },
        {
          key: "status",
          label: "状态",
          value: getStatusText(asset.status),
          type: "tag" as const,
          tagType: getStatusTagType(asset.status) as
            | "success"
            | "warning"
            | "info"
            | "danger"
            | "",
        },
      ],
    },
    {
      title: "匹配内容",
      type: "normal" as const,
      items: [
        {
          key: "matched_content",
          label: "代码片段",
          value: asset.matched_content || "-",
          type: "custom" as const,
          slot: "matched_content",
          span: 2,
        },
      ],
    },
  ];
});

onMounted(() => {
  loadDepartments();
  fetchAssetList();
});

defineExpose({
  fetchAssetList,
});
</script>

<template>
  <div class="github-asset-management">
    <el-card style="margin-bottom: 20px">
      <DynamicForm
        :form-config="formConfig"
        :model-value="filterForm"
        type="search"
        ref="formRef"
        @search="handleSearch"
        @reset="handleReset"
      />
    </el-card>
    <el-card>
      <DynamicTable
        :pagination="pagination"
        :columns="historyColumns"
        :data="assetList"
        :loading="loading"
        :showToolbar="true"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template #asset_action="{ row }">
          <el-button type="primary" size="small" @click="handleViewDetail(row)"
            >详情
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 资产详情对话框 -->
    <DynamicDetailDialog
      v-model="showDetailDialog"
      title="资产详情"
      :groups="detailGroups"
      :loading="loadingDetail"
    >
      <template #matched_content="{ value }">
        <div class="code-snippet-container">
          <pre class="code-block"><code>{{ value || "-" }}</code></pre>
        </div>
      </template>
      <template #repository_url="{ value }">
        <a
          v-if="value && value !== '-'"
          :href="value"
          target="_blank"
          rel="noopener noreferrer"
          class="repository-link"
        >
          {{ value }}
        </a>
        <span v-else>-</span>
      </template>
    </DynamicDetailDialog>
  </div>
</template>

<style scoped lang="scss">
.github-asset-management {
  padding: 20px;
}

.repository-link {
  color: #409eff;
  text-decoration: none;
  word-break: break-all;
  transition: color 0.3s;

  &:hover {
    color: #66b1ff;
    text-decoration: underline;
  }

  &:visited {
    color: #409eff;
  }
}

.code-snippet-container {
  width: 100%;
  max-height: 400px;
  overflow: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #3c3c3c;
  padding: 0;

  .code-block {
    margin: 0;
    padding: 12px;
    font-family: "Monaco", "Menlo", "Ubuntu Mono", "Consolas", "source-code-pro",
      "Courier New", monospace;
    font-size: 13px;
    line-height: 1.6;
    color: #ffffff;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-wrap: break-word;
    background: transparent;

    code {
      display: block;
      font-family: inherit;
      font-size: inherit;
      color: inherit;
      background: transparent;
      padding: 0;
      margin: 0;
    }
  }

  &::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #c1c1c1;
    border-radius: 4px;

    &:hover {
      background-color: #a8a8a8;
    }
  }

  &::-webkit-scrollbar-track {
    background-color: #f1f1f1;
    border-radius: 4px;
  }
}
</style>
